<template>
  <header class="header-container">
    <div class="header-content">
      <!-- Logo区域 -->
      <router-link to="/home" class="logo">
        <i class="fas fa-utensils logo-icon"></i>
        <h1>食尚先锋</h1>
      </router-link>

      <!-- 导航菜单 -->
      <nav class="nav-menu">
        <ul>
          <li>
            <router-link to="/home" class="nav-link" active-class="active">
              <span class="icon"><i class="fas fa-home"></i></span>
              <span>首页</span>
            </router-link>
          </li>
          <li>
            <router-link to="/home/products" class="nav-link" active-class="active">
              <span class="icon"><i class="fas fa-utensils"></i></span>
              <span>商品中心</span>
            </router-link>
          </li>
          <li>
            <router-link to="/home/orders" class="nav-link" active-class="active">
              <span class="icon"><i class="fas fa-clipboard-list"></i></span>
              <span>我的订单</span>
            </router-link>
          </li>
          <li>
            <router-link to="/home/cart" class="nav-link" active-class="active">
              <span class="icon"><i class="fas fa-shopping-cart"></i></span>
              <span>购物车</span>
              <span class="cart-count" v-if="cartCount > 0">{{ cartCount }}</span>
            </router-link>
          </li>
        </ul>
      </nav>

      <!-- 用户信息区域 -->
      <div class="user-area" @click="toggleUserMenu">
        <div class="user-avatar">
          <img :src="user.avatar || defaultAvatar" alt="用户头像" />
        </div>
        <span class="user-name">{{ user.name || '未登录' }}</span>
        <i class="fas fa-chevron-down" :class="{ 'rotate-180': showUserMenu }"></i>

        <!-- 用户菜单下拉框 -->
        <transition name="fade">
          <div class="user-menu" v-show="showUserMenu" @click.stop>
            <div class="user-menu-header">
              <div class="user-menu-avatar">
                <img :src="user.avatar || defaultAvatar" alt="用户头像" />
              </div>
              <div class="user-menu-info">
                <div class="user-menu-name">{{ user.name || '未登录' }}</div>
                <div class="user-menu-phone">{{ user.phone || '未绑定手机' }}</div>
              </div>
            </div>
            <ul>
              <li @click="goToProfile">
                <i class="fas fa-user-circle"></i>
                <span>个人中心</span>
              </li>
              <li @click="UserLogout">
                <i class="fas fa-sign-out-alt"></i>
                <span>退出登录</span>
              </li>
            </ul>
          </div>
        </transition>
      </div>
    </div>
  </header>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import defaultAvatar from '@/assets/images/user/img.png';
import { getUserInfo } from "@/api/user";
import { getUsernameFromToken } from "@/utils/jwtUitl";
import { getToken, logout } from "@/utils/auth";
import { ElMessageBox } from "element-plus";
import { getCartCount } from "@/api/cart";

const router = useRouter();
const route = useRoute();
const showUserMenu = ref(false);
const cartCount = ref(0); // 购物车数量，初始为0
const user = ref({
  name: '未知用户',
  avatar: ''
});

// 切换用户菜单显示状态
const toggleUserMenu = () => {
  showUserMenu.value = !showUserMenu.value;
};

// 前往个人中心
const goToProfile = () => {
  router.push('/home/profile');
  showUserMenu.value = false;
};

// 退出登录
const UserLogout = async() => {
  try {
    await ElMessageBox.confirm(
        '确定要退出登录吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          draggable: true, // 可拖动弹窗
          closeOnClickModal: false // 必须点击按钮关闭
        }
    )
    // 用户点击确定
    logout() //auth.js
  } catch (error) {
    // 用户点击取消
    console.log('取消退出')
  }
  showUserMenu.value = false;
};

// 点击外部关闭用户菜单
const closeUserMenu = (e) => {
  if (!e.target.closest('.user-area')) {
    showUserMenu.value = false;
  }
};

// 获取购物车数量
const fetchCartCount = async () => {
  try {
    const res = await getCartCount();
    if (res.code === '200') {
      cartCount.value = res.data || 0;
    } else {
      console.log("获取购物车数量失败");
      cartCount.value = 0;
    }
  } catch (error) {
    console.error("获取购物车数量出错:", error);
    cartCount.value = 0;
  }
};

//填充用户信息
const fillUserInfo = async () => {
  //首先从token中获取到用户的手机号
  const phone = getUsernameFromToken(getToken())
  if (phone) {
    const res = await getUserInfo(phone)
    if (res.code === '200') {
      user.value = res.data
    }else{
      console.log("获取用户信息失败");
    }
  } else {
    console.log("phone为空");
  }
}

// 监听路由变化，在特定页面更新购物车数量
watch(() => route.path, (newPath) => {
  // 当用户访问首页、商品页、购物车页或从这些页面返回时，更新购物车数量
  if (newPath.includes('/home') || newPath.includes('/products') || newPath.includes('/cart')) {
    fetchCartCount();
  }
});

// 添加全局点击事件监听
onMounted(() => {
  document.addEventListener('click', closeUserMenu);
  //从后端api获取到用户信息
  fillUserInfo();
  // 获取购物车数量
  fetchCartCount();
  
  // 添加自定义事件监听，用于其他组件通知购物车数量变化
  window.addEventListener('cart-updated', fetchCartCount);
});

// 组件卸载时移除事件监听
onUnmounted(() => {
  document.removeEventListener('click', closeUserMenu);
  window.removeEventListener('cart-updated', fetchCartCount);
});
</script>

<style scoped>
.header-container {
  background-color: #fff;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  z-index: 1000;
  height: 70px;
  transition: all 0.3s ease;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.logo {
  text-decoration: none;
  color: #ff6b6b;
  display: flex;
  align-items: center;
}

.logo-icon {
  font-size: 24px;
  margin-right: 10px;
  color: #ff6b6b;
}

.logo h1 {
  margin: 0;
  font-size: 24px;
  background: linear-gradient(to right, #ff6b6b, #ff8e53);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-weight: 700;
  letter-spacing: 0.5px;
}

.nav-menu ul {
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0;
}

.nav-menu li {
  margin: 0 15px;
}

.nav-link {
  text-decoration: none;
  color: #333;
  font-size: 16px;
  font-weight: 500;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px 12px;
  border-radius: 8px;
  transition: all 0.3s ease;
  position: relative;
}

.nav-link:hover {
  color: #ff6b6b;
  background-color: #fff5f5;
  transform: translateY(-2px);
}

.nav-link.active {
  color: #ff6b6b;
  background-color: #fff5f5;
  box-shadow: 0 2px 8px rgba(255, 107, 107, 0.2);
}

.nav-link .icon {
  font-size: 18px;
  margin-bottom: 4px;
}

.cart-count {
  position: absolute;
  top: -5px;
  right: -5px;
  background: linear-gradient(to right, #ff6b6b, #ff8e53);
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  font-weight: bold;
  box-shadow: 0 2px 5px rgba(255, 107, 107, 0.3);
}

.user-area {
  display: flex;
  align-items: center;
  cursor: pointer;
  position: relative;
  padding: 8px 15px;
  border-radius: 25px;
  transition: all 0.3s ease;
}

.user-area:hover {
  background-color: #f5f5f5;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 10px;
  border: 2px solid #ff6b6b;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-name {
  font-size: 15px;
  font-weight: 500;
  margin-right: 8px;
  color: #333;
}

.fa-chevron-down {
  transition: transform 0.3s ease;
  font-size: 12px;
  color: #666;
}

.rotate-180 {
  transform: rotate(180deg);
}

.user-menu {
  position: absolute;
  top: 55px;
  right: 0;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
  width: 220px;
  overflow: hidden;
  z-index: 1001;
  border: 1px solid #eee;
}

.user-menu-header {
  padding: 15px;
  background: linear-gradient(to right, #ff6b6b, #ff8e53);
  color: white;
  display: flex;
  align-items: center;
}

.user-menu-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 10px;
  border: 2px solid white;
}

.user-menu-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-menu-info {
  flex: 1;
}

.user-menu-name {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 3px;
}

.user-menu-phone {
  font-size: 12px;
  opacity: 0.9;
}

.user-menu ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.user-menu li {
  padding: 12px 15px;
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
  border-bottom: 1px solid #f5f5f5;
}

.user-menu li:last-child {
  border-bottom: none;
}

.user-menu li:hover {
  background-color: #f5f5f5;
  color: #ff6b6b;
}

.user-menu li i {
  margin-right: 10px;
  width: 16px;
  text-align: center;
  color: #ff6b6b;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease, transform 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

@media (max-width: 768px) {
  .header-container {
    height: 60px;
  }

  .header-content {
    padding: 0 10px;
  }

  .logo h1 {
    font-size: 20px;
  }

  .logo-icon {
    font-size: 20px;
  }

  .nav-link span:not(.icon) {
    display: none;
  }

  .nav-link .icon {
    font-size: 20px;
    margin-bottom: 0;
  }

  .user-name {
    display: none;
  }

  .user-avatar {
    width: 32px;
    height: 32px;
    margin-right: 0;
  }

  .nav-menu li {
    margin: 0 8px;
  }
}
</style>